import torch
from sklearn.metrics import classification_report, accuracy_score

# 假设model是你的模型实例，已经加载了训练好的权重
# 假设test_loader是你的测试集DataLoader

model.eval()  # 设置模型为评估模式
true_labels = []
pred_labels = []

with torch.no_grad():  # 在评估模式下关闭梯度计算，节省内存和加速计算
    for inputs, labels in test_loader:
        outputs = model(inputs)  # 前向传播获取预测结果
        _, predicted = torch.max(outputs.data, 1)  # 获取预测标签
        true_labels.extend(labels.tolist())
        pred_labels.extend(predicted.tolist())

# 计算性能指标
accuracy = accuracy_score(true_labels, pred_labels)
report = classification_report(true_labels, pred_labels)

print(f"Accuracy: {accuracy}")
print(report)



from flask import Flask, request, jsonify
import torch

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    # 假设这里有一个函数load_model()用于加载模型，且model是一个全局变量
    # model = load_model()

    data = request.get_json()  # 假设客户端发送的是JSON格式的数据
    # 这里需要对data进行处理，转换成模型可以接受的输入格式
    # processed_data = ...

    with torch.no_grad():
        prediction = model(processed_data)  # 假设model的前向传播已经能够处理单个样本
        predicted_label = torch.argmax(prediction).item()

    return jsonify({'prediction': predicted_label})

if __name__ == '__main__':
    app.run(debug=True)

